﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quartz;
using Task.Log;

namespace Task.Quartz
{
    public class QJob : QJobEntity, IQJob
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public QJob() { }

        public QJob(QJobEntity qjob)
        {
            base.JobId = qjob.JobId;
            base.SysCode = qjob.SysCode;
            base.Name = qjob.Name;
            base.Group = qjob.Group;
            base.Seconds = qjob.Seconds;
            base.MaxTimes = qjob.MaxTimes;
            base.WithCronSchedule = qjob.WithCronSchedule;
            base.StartTime = qjob.StartTime;
            base.HandlerConfig = qjob.HandlerConfig;
            Handler = null;
            DetailHandler = null;
        }

        [System.Xml.Serialization.XmlIgnore]
        public Action Handler { get; set; }
        [System.Xml.Serialization.XmlIgnore]
        public Action<IQJob> DetailHandler { get; set; }
        
        /// 持久化保存
        /// </summary>
        public bool Save()
        {
            try
            {
                string filepath = JobFactory.Instance.GetPath();
                if (!File.Exists(Path())) return false;
                IQJob myjob = new QJob()
                {
                    SysCode = this.SysCode,
                    JobId = this.JobId,
                    Group = this.Group,
                    Name = this.Name,
                    LastTime = this.LastTime,
                    Handler = this.Handler,
                    MaxTimes = this.MaxTimes,
                    WithCronSchedule = this.WithCronSchedule,
                    Seconds = this.Seconds,
                    State = this.State,
                    Times = this.Times,
                    StartTime = this.StartTime,
                    DetailHandler = this.DetailHandler,
                    Action = this.Action
                };
                string xml = XMLProcess.Serializer(typeof(QJob), myjob);
                XMLProcess.Write(xml, Path());
                return true;
            }
            catch (Exception ex)
            {
                //Log.LogHelper.Fatal(ex.ToString(), System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                return false;
            }
        }

        public bool Load()
        {
            try
            {
                if (!File.Exists(Path())) return false;
                var job = XMLProcess.Deserialize<QJob>(XMLProcess.ReadXml(Path()));
                base.JobId = job.JobId;
                base.SysCode = job.SysCode;
                base.Name = job.Name;
                base.Group = job.Group;
                base.Seconds = job.Seconds;
                base.MaxTimes = job.MaxTimes;
                base.WithCronSchedule = job.WithCronSchedule;
                base.StartTime = job.StartTime;
                base.Times = job.Times;
                base.State = job.State;
                base.Action = job.Action;
                base.LastTime = job.LastTime;
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Fatal(ex.ToString(), System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                return false;
            }
        }

        /// <summary>
        /// 任务的jobkey规则
        /// </summary>
        /// <returns></returns>
        public string Key()
        {
            return SysCode + "_" + JobId;
        }

        /// <summary>
        /// 开始执行任务
        /// </summary>
        public void Start()
        {
            JobFactory.Instance.BuildBySimple(this);
        }

        public void Start(ITrigger trigger)
        {
            JobFactory.Instance.BuildBySimple_Treggger(this, trigger);
        }

        /// <summary>
        /// 开始执行任务
        /// </summary>
        /// <param name="starttime">开始执行时间</param>
        /// <param name="internaltimes">时间间隔(s)</param>
        /// <param name="maxtimes">执行次数</param>
        public void StartBySimple()
        {
            JobFactory.Instance.BuildBySimple(this);
        }

        public void StartByCron()
        {
            JobFactory.Instance.BuildByCronSchedule(this);
        }

        /// <summary>
        /// 下次执行时间
        /// </summary>
        /// <returns></returns>
        public DateTime NextTime()
        {
            return LastTime.AddSeconds(Seconds);
        }

        /// <summary>
        ///任务触发动作
        /// </summary>
        /// <param name="handler">需要任务信息的动作</param>
        /// <returns>IMyJob</returns>
        public IQJob Handle(Action handler)
        {
            Handler = handler;
            return this;
        }

        /// <summary>
        /// 任务触发动作
        /// </summary>
        /// <param name="handler">需要任务信息的动作</param>
        /// <returns>IMyJob</returns>
        public IQJob Handle(Action<IQJob> handler)
        {
            DetailHandler = handler;
            return this;
        }

        /// <summary>
        /// 持久化地址
        /// </summary>
        /// <returns>【例：../job/syscode_name_group_jobid.xml】</returns>
        public string Path()
        {
            return System.IO.Path.Combine(JobFactory.Instance.GetPath(), string.Format("{0}_{1}_{2}_{3}.xml", SysCode, Group, Name, JobId));
        }

        /// <summary>
        /// 移除任务
        /// </summary>
        /// <returns></returns>
        public bool Remove()
        {
            return JobFactory.Instance.Remove(Key());
        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        public void Pause()
        {
            JobFactory.Instance.Pause(Key());
        }

        /// <summary>
        /// 继续执行任务
        /// </summary>
        public void Resume()
        {
            JobFactory.Instance.Resume(Key());
        }
    }
}

